import type { Request, Response } from 'express';
import {
  responseSuccess,
  responseError,
  responseData,
} from '@/share/interface/standard';
import Base from '@/controller/public/MiniBaseController';
import { uploadHandle, FILE_PATH } from '@/middleware/multer';
const fs = require('fs');
const path = require('path');

export class KnowledgeController extends Base {
  async findAll(req: Request) {
    const { channel } = req.query;
    const knowledge_list =
      await this.knowledgeClassroomRepository.find({
        where: { channel, deleted: false },
        order: { created: 'DESC' },
        relations: ['collect_user'],
      });
    return responseSuccess(knowledge_list);
  }

  async findOneAndIncrease(req: Request) {
    const id = parseInt(req.params.id);
    const knowledge = await this.knowledgeClassroomRepository.findOne(
      {
        where: { id },
      }
    );
    if (!knowledge) return responseError('知识条目不存在');

    await this.knowledgeClassroomRepository.update(
      { id },
      { view: knowledge.view + 1 }
    );

    return responseSuccess(knowledge);
  }

  // 给用户添加知识库收藏
  async collectForUser(req: Request) {
    const { user_id = req.user_id, knowledge_id } = req.body;
    if (isNaN(user_id)) {
      return responseError('无效的用户ID');
    }
    const user = await this.userRepository.findOne({
      where: { id: user_id },
      relations: ['collect_knowledge'],
    });
    if (!user)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    if (!knowledge_id) return responseError('知识条目不存在');
    const knowledge = await this.knowledgeClassroomRepository.findOne(
      {
        where: { id: knowledge_id },
      }
    );
    if (!knowledge) return responseError('知识条目不存在');

    user.collect_knowledge = [...user.collect_knowledge, knowledge];
    await this.userRepository.save(user);
    return responseSuccess('收藏成功');
  }

  async getCollectForUser(req: Request) {
    const { user_id = req.user_id } = req.body;
    if (!user_id)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    const user = await this.userRepository.findOne({
      where: { id: user_id },
      relations: ['collect_knowledge'],
      select: ['id', 'collect_knowledge'],
    });
    if (!user)
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    return responseSuccess(user.collect_knowledge);
  }

  async addKnowledge(req: Request, res: Response) {
    const final_file = await uploadHandle(req, res);
    const { channel, title, author, content, id } = req.body;
    if (!final_file && !id) return responseError('上传失败');
    let type: string = '';
    if (final_file) {
      switch (final_file?.mimetype) {
        case 'image/jpeg':
        case 'image/png':
          type = 'text';
          break;
        case 'video/mp4':
          type = 'video';
          break;
        default:
          return responseError('不支持的文件类型');
      }
    }
    console.log(final_file);
    if (+id) {
      const knowledge =
        await this.knowledgeClassroomRepository.findOne({
          where: { id: +id },
        });
      await this.knowledgeClassroomRepository.save({
        id: +id,
        author,
        title,
        content,
        channel,
        url: final_file
          ? final_file.final_host + final_file.filename
          : knowledge.url,
      });
      return responseSuccess('上传成功');
    }

    await this.knowledgeClassroomRepository.save({
      author,
      title,
      type,
      content,
      url: final_file.final_host + final_file.filename,
    });
    return responseSuccess();
  }

  async deleteKnowledge(req: Request, res: Response) {
    const id = parseInt(req.params.id);
    const knowledge =
      await this.knowledgeClassroomRepository.findOneBy({
        id,
      });
    if (!knowledge) return responseError('知识条目不存在');

    try {
      knowledge.deleted = true;
      await this.knowledgeClassroomRepository.save(knowledge);

      // await this.knowledgeClassroomRepository.delete(id);
      // const filePathToDelete = path.join(
      //   FILE_PATH,
      //   path.basename(knowledge.url)
      // );
      // if (fs.existsSync(filePathToDelete)) {
      //   fs.unlinkSync(filePathToDelete); // 同步删除文件
      // }
      return responseSuccess('删除成功');
    } catch (error) {
      // 处理删除过程中可能出现的任何错误
      console.error('删除知识条目时出错:', error);
      return responseError(error);
    }
  }
}
